package com.apobates.jforum2.troll.accounts.biz.impl.dao;

import com.apobates.jforum2.troll.accounts.biz.dao.ForumScoreRoleDao;
import com.apobates.jforum2.troll.accounts.entity.ForumScoreRole;
import java.util.Optional;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author xiaofanku
 * @since 20200515
 */
@Repository
public class ForumScoreRoleDaoImpl implements ForumScoreRoleDao{
    @PersistenceContext
    private EntityManager entityManager;
    private final static Logger logger = LoggerFactory.getLogger(ForumScoreRoleDaoImpl.class);
    
    @Override
    public Stream<ForumScoreRole> findAllUsed() {
        return entityManager.createQuery("SELECT fsr FROM ForumScoreRole fsr WHERE fsr.status = ?1", ForumScoreRole.class).setParameter(1, true).getResultStream();
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(ForumScoreRole entity) {
        entityManager.persist(entity);
    }
    
    @Override
    public Optional<ForumScoreRole> findOne(Integer primaryKey) {
        return Optional.ofNullable(entityManager.find(ForumScoreRole.class, primaryKey));
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Optional<Boolean> edit(ForumScoreRole updateEntity) {
        try {
            entityManager.merge(updateEntity);
            return Optional.of(true);
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug(e.getMessage(), e);
            }
            return Optional.empty();
        }
    }
    
    @Override
    public Stream<ForumScoreRole> findAll() {
        return entityManager.createQuery("SELECT fsr FROM ForumScoreRole fsr", ForumScoreRole.class).getResultStream();
    }
    
    @Override
    public long count() {
        return -1L;
    }
}